// pages/floor/template/tpl69/tpl69.js
import * as API_Promotions from '../../../api/promotions.js';
import { Foundation } from '../../../ui-utils/index'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tplItemData: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 时间
    time: false,
    // 商品列表
    goodsList: [],
    // 时间
    times: {
      hours: '00',
      minutes: '00',
      seconds: '00'
    },
    // 当前这一场的时刻信息
    timeLine: '',
    // 是否只有一场
    onlyOne: false
  },
  // 生命周期
  lifetimes: {
    async ready() {
      const _tplData = this.properties.tplItemData;
      this.GET_TimeLine();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {/** 开始倒计时 */
    startCountDown: function () {
      this.interval = setInterval(() => {
        let { time } = this.data;
        // if (time <= 0) {
        //   clearInterval(this.interval)
        //   this.$alert(this.onlyOne ? '本轮限时抢购已结束！' : '下一轮限时抢购已经开始啦！请确认查看', function () {
        //     location.reload()
        //   })
        //   return false
        // }
        time -= 1;
        const timeText = Foundation.countTimeDown(time);
        this.setData({
          time: time,
          times: timeText
        });
      }, 1000)
    },
    /** 获取时间段 */
    GET_TimeLine: function () {
      API_Promotions.getSeckillTimeLine().then(response => {
        if (!response || !response.length) {
          return
        };
        response = response.sort((x, y) => (Number(x.time_text) - Number(y.time_text)))
        const onlyOne = response.length === 1
        this.setData({
          onlyOne: onlyOne,
          time: response[0].distance_time !== 0 ? response[0].distance_time : onlyOne ? Foundation.theNextDayTime() : response[1].distance_time,
          timeLine: response[0]
        });
        this.startCountDown()
        this.GET_GoodsList(response[0].time_text)
      })
    },
    /** 获取商品列表 */
    GET_GoodsList: function (range_time) {
      API_Promotions.getSeckillTimeGoods({ range_time }).then(response => {
        this.setData({
          goodsList: response.data
        });
      })
    }
  },
  onUnload: function () {
    this.interval && clearInterval(this.interval)
  }
})
